//
//  RequestManager.m
//  AJPushDemo
//
//  Created by kean_qi on 2021/3/17.
//

#import "RequestManager.h"

@implementation RequestManager
+ (instancetype)sharedInstance {
    static id _instance;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (void)GETRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail{
    NSMutableString *strM = [[NSMutableString alloc] init];
    [paramaters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        // 服务器接收参数的 key 值.
        NSString *paramaterKey = key;
        // 参数内容
        NSString *paramaterValue = obj;
        // appendFormat :可变字符串直接拼接的方法!
        [strM appendFormat:@"%@=%@&",paramaterKey,paramaterValue];
    }];
    
    urlString = [NSString stringWithFormat:@"%@?%@",urlString,strM];
    // 截取字符串的方法!
    urlString = [urlString substringToIndex:urlString.length - 1];
    NSLog(@"urlString:%@",urlString);
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
    // 2. 发送网络请求.
    // completionHandler: 说明网络请求完成!
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        // 网络请求成功:
        if (data && !error) {
            // 查看 data 是否是 JSON 数据.
            // JSON 解析.
            id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            // 如果 obj 能够解析,说明就是 JSON
            if (!obj) {
                obj = data;
            }
            // 成功回调
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    success(obj,response);
                }
            });
        } else {
            // 失败回调
            if (fail) {
                fail(error);
            }
        }
    }] resume];
}

//POST请求方法
- (void)POSTRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail {
//    NSMutableString *strM = [[NSMutableString alloc] init];
//    [paramaters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
//        // 服务器接收参数的 key 值.
//        NSString *paramaterKey = key;
//        // 参数内容
//        NSString *paramaterValue = obj;
//        // appendFormat :可变字符串直接拼接的方法!
//        [strM appendFormat:@"%@=%@&",paramaterKey,paramaterValue];
//
//    }];
//    NSString *body = [strM substringToIndex:strM.length - 1];
//    NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",urlString);
    NSLog(@"%@",paramaters);
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
    // 1.设置请求方法:
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // 2.设置请求体
//    request.HTTPBody = bodyData;
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:paramaters options:NSJSONWritingPrettyPrinted error:nil];
    // 2. 发送网络请求.
    // completionHandler: 说明网络请求完成!
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 网络请求成功:
        if (data && !error) {
            // 查看 data 是否是 JSON 数据.
            // JSON 解析.
            id obj = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:NULL];
            NSLog(@"%@",obj);
            // 如果 obj 能够解析,说明就是 JSON
            if (!obj) {
                obj = data;
            }
            // 成功回调
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    success(obj,response);
                }
            });
        } else {
            // 失败回调
            if (fail) {
                fail(error);
            }
        }
    }] resume];
    
}


@end
